package com.hxh.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/9/6 20:14
 * ReentrantLock 可重入锁
 */
public class LSaleTicket {

    public static void main(String[] args) {
        LTicket ticket = new LTicket();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "CC").start();
    }
}

// 资源类
class LTicket {
    // 票数
    private int num = 30;

    // 可重入锁
    private final ReentrantLock lock = new ReentrantLock();

    // 买票
    public void sale() {
        lock.lock(); // 上锁
        try {
            if (num > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了第 " + (num--) + "张票, 剩余票数: " + num);
            }
        } finally {
            lock.unlock(); // 解锁
        }
    }
}
